<template>
  <div class="upload-img-contain">
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :http-request="handleImg"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <i v-if="value" class="el-icon-error" @click="closeImg" />
  </div>
</template>

<script>
// 导包
import COS from 'cos-js-sdk-v5'
// 实例化
// AKIDgBRQ8ZjcEZdRxCArITN0LPCixvc1HFwM
// B5i49wShgNnwnOikV0EBrGOEn44nFPJw
const cos = new COS({
  SecretId: 'AKIDgBRQ8ZjcEZdRxCArITN0LPCixvc1HFwM', // 身份识别 ID
  SecretKey: 'B5i49wShgNnwnOikV0EBrGOEn44nFPJw' // 身份密钥
})
export default {
  //   data() {
  //     return {
  //       imageUrl: ''
  //     }
  //   },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    handleImg(params) {
      cos.putObject(
        {
          Bucket: 'rm-admin-1306581536' /* 容器名 必须 */,
          Region: 'ap-shenzhen-fsi' /* 存储桶所在地域，必须 */,
          Key: params.file.name /* 文件标记,可以用名字代替 必须 */,
          StorageClass: 'STANDARD' /* 固定值可以不管他 必须 */,
          Body: params.file, // 上传文件对象
          onProgress: progressData => {
            // 上传进度
            // console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // 有错就是err 没错就是 data
          // console.log(err || data)
          // console.log('err', err)
          if (data.statusCode === 200) {
            // this.imgUrl = 'https://' + data.Location
            this.$emit('input', 'https://' + data.Location)
          }
        }
      )
    },
    beforeAvatarUpload(file) {
      const isJPG = [
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
      ].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG jpeg gif png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }

      return isJPG && isLt2M
    },
    closeImg() {
      this.$emit('input', '')
    }
  }
}
</script>
<style lang="scss">
.upload-img-contain {
  width: 178px;
  height: 178px;
  position: relative;
  .el-icon-error {
    position: absolute;
    top: -10px;
    right: -10px;
    font-size: 10px;
    color: red;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
